<?php

namespace App\Http\Controllers\Workflow\internal;

use App\Enums\Workflow\WorkflowEnum;
use App\Http\Controllers\BaseController;
use App\Models\Kms\User\KmsUser;
use App\Models\Workflow\WorkflowOrderLogModel;
use App\Models\Workflow\WorkflowOrderModel;
use App\Service\Workflow\WorkflowOrderService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class SupplierTenderController extends BaseController
{
    public function init(Request $request)
    {
        $relationId = (int)$request->get('relationId');
        $uid        = (int)$request->get('uid');

        $this->validate($request, [
            'uid'        => 'required|integer',
            'relationId' => 'required|integer',
        ]);

        $workflow = (new WorkflowOrderService)->init(WorkflowEnum::WORKFLOW_TYPE_SUPPLIER_TENDER, 0, $relationId, $uid);

        return $this->success((new WorkflowOrderService($workflow->id))->orderInfo());
    }

    public function order(Request $request, int $id)
    {
        $data = (new WorkflowOrderService($id))->orderInfo();

        return $this->success($data);
    }

    public function orders(Request $request)
    {
        $ids = $request->get('ids');

        $data          = WorkflowOrderModel::query()->whereIn('id', $ids)->get();
        $createdByUids = $data->pluck('createdByUid');
        $fsUsers       = KmsUser::query()
                                ->whereIn('rmsUserId', $createdByUids)
                                ->where('rmsUserId', '>', 0)
                                ->select('rmsUserId', 'name', 'nickname')
                                ->get()
                                ->keyBy('rmsUserId')
                                ->toArray();

        $data = $data->map(function ($item) use ($fsUsers) {

            $user = $fsUsers[$item->createdByUid] ?? [];
            if (!$user) {
                $item->createdByUsername = '';
            } else {
                $item->createdByUsername = $user['name'] . '（' . $user['nickname'] . '）';
            }

            $item->timestamps = false;
            $item->createdAt  = date('Y-m-d H:i:s', $item->createdAt);
            unset($item->updatedAt);

            return $item;
        })->toArray();

        return $this->success($data);
    }

    public function audit(Request $request, int $id)
    {
        $uid          = $request->get('uid');
        $cNodeId      = $request->get('cNodeId');
        $auditStatus  = $request->get('auditStatus');
        $auditContent = $request->get('auditContent');
        $rejectNodeId = (int)$request->get('rejectNodeId');

        $this->validate($request, [
            'uid'          => 'required|integer',
            'cNodeId'      => 'required|integer',
            'auditStatus'  => 'required|integer|in:1,2',
            'auditContent' => 'required|string',
            'rejectNodeId' => 'required_if:auditStatus,2|integer'
        ]);

        // 节点状态切换 + 日志更新
        (new WorkflowOrderService($id))
            ->checkHandlerUid($uid)
            ->finishNodeEnterNext($cNodeId, $auditStatus, $auditContent, $rejectNodeId);

        return $this->success((new WorkflowOrderService($id))->orderInfo());
    }

    public function addLog(Request $request)
    {
        $this->validate($request, [
            'workflowOrderId'     => 'required|integer',
            'workflowOrderNodeId' => 'required|integer',
            'nodeName'            => 'required|string',
            'handlerName'         => 'required|string',
            'audit'               => 'required|integer|' . Rule::in(array_keys(WorkflowOrderLogModel::AUDIT_TEXT)),
            'status'              => 'required|integer',
            'createdAt'           => 'required|integer',
        ]);

        WorkflowOrderLogModel::query()
                             ->insert([
                                 'workflowOrderId'     => $request->get('workflowOrderId'),
                                 'workflowOrderNodeId' => $request->get('workflowOrderNodeId'),
                                 'nodeName'            => $request->get('nodeName'),
                                 'handlerUid'          => $request->get('handlerUid'),
                                 'handlerName'         => $request->get('handlerName'),
                                 'audit'               => $request->get('audit'),
                                 'rejectNodeId'        => 0,
                                 'status'              => $request->get('status'),
                                 'createdAt'           => $request->get('createdAt'),
                                 'updatedAt'           => $request->get('createdAt'),
                             ]);

        return $this->success();
    }

    public function logs(Request $request, int $id)
    {
        $lists = WorkflowOrderLogModel::query()->where('workflowOrderId', $id)->orderBy('createdAt')->get()->toArray();

        return $this->success($lists);
    }
}
